import { observer, useLocalObservable } from 'mobx-react'
import React, { useEffect, useRef, useState } from 'react'
import select from '@/resource/level/select.png'
import { Swiper, Toast } from 'antd-mobile'
import { useHistory } from 'umi'
import styles from './index.module.less'
import type { levelListType } from '@/pages/level/interface'
import Store from '@/pages/level/store'
import type { SwiperRef } from 'antd-mobile/es/components/swiper'
import { getData } from '@/servers/http'
import { api } from '@/servers/api'
import { setUserCenterCookies } from '@/utils/userCenter'
import dayjs from 'dayjs'

let hasClick = false
export default observer((props: any) => {
    const { renderData, getSwiperValue, id, isSubmitTraining, value } = props
    const store = useLocalObservable(() => new Store())
    const history = useHistory()
    const swiperRef = useRef<SwiperRef>()

    //开始任务
    const startTask = (item: levelListType, i: number) => {
        if (hasClick) {
            return
        }
        hasClick = true
        getData(api.userBarriersScoreInfo)
            .then(({ data: scoreInfo }) => {
                const { is_score, is_course_score } = scoreInfo
                if (Number(is_score) === 1) {
                    Toast.show(Number(is_course_score) === 1 ? '讲师已评分' : '讲师已评审')
                    return
                } else {
                    return getData(api.usersLoginUserInfo).then((res: any) => {
                        const { data, status } = res
                        if (status !== 200) return
                        const { platform_access_token, mid_domain, open_key, userStudent } = data || {}
                        let callbackUrl = ''
                        // 结班时间
                        if (dayjs().isAfter(dayjs(userStudent.end_class_time).endOf('day')) && item.is_player === '0') {
                            Toast.show('当前已结束培训')
                            return
                        }
                        //  1.图片上传 2. 五指图 3.表单填写类 4.测评-MBTI 5.测评-职业兴趣密码 6.我的面试【直播】  7.意向岗位 8.完善简历 9.职业能力分析测评【废弃】
                        // 关卡类型 1.问卷调查 2. 五指图 3.简历 4.意向岗位 5.生涯彩虹图
                        switch (item.type) {
                            case '1':
                                if (item.is_player === '1') {
                                    history.push(`/questionnaire/result/${item.id}`)
                                    return
                                }
                                if (status !== 200) return
                                const { platform_site_id, platform_site_alias, platform_usercode } = data || {}
                                callbackUrl = encodeURIComponent(window.location.origin + `/#/questionnaire/result/${item?.id}`)
                                setUserCenterCookies(
                                    {
                                        h5Token: platform_access_token,
                                        h5SelectUserType: '1',
                                        h5UserCode: platform_usercode,
                                        h5Alias: platform_site_alias,
                                    },
                                    platform_site_id,
                                )
                                window.location.href = `${mid_domain}/question-center/collecting?code=${item?.code}&h5Back=${callbackUrl}&fill=edit`
                                break
                            case '2':
                                if (item.is_player === '1') {
                                    history.push(`/chartresult?id=${item.id}`)
                                } else {
                                    history.push(`/careerredact?id=${item.id}`)
                                }
                                break
                            case '3':
                                history.push(`/resume/choose`)
                                // callbackUrl = encodeURIComponent(window.location.origin + `/#/level?id=${item?.scene_id}`)
                                // if (item.is_player === '1') {
                                //     window.location.href = `${mid_domain}/job-center/my-resume/view?title=${item.name}&token=${platform_access_token}&callback=${callbackUrl}`
                                //     return
                                // }
                                // window.location.href = `${mid_domain}/job-center/my-resume?title=${item.name}&token=${platform_access_token}&callback=${callbackUrl}`
                                break
                            case '4':
                                if (item.is_player === '1') {
                                    history.push(`/intended/result?id=${item.id}`)
                                    return
                                }
                                callbackUrl = encodeURIComponent(window.location.origin + `/#/intended/result?id=${item?.id}`)
                                window.location.href = `${mid_domain}/job-center/intended-position/index?token=${platform_access_token}&callback=${callbackUrl}&openKey=`
                                break

                            case '5':
                                if (item.is_player === '1') {
                                    history.push(`/rainbow/result/${item.id}?id=${item.id}`)
                                } else {
                                    history.push(`/rainbow/step1/${item.id}?id=${item.id}`)
                                }
                                break
                            default:
                                break
                        }
                    })
                }
            })
            .finally(() => {
                hasClick = false
            })
    }
    //提交测评
    const onSubmit = () => {
        store.putTraining(id)
    }
    //判断是否全部完成
    const isAllPlay = () => {
        let arr = renderData && renderData.filter((item: levelListType) => item.is_player === '0')
        if (!arr.length) {
            return true
        } else {
            return false
        }
    }

    //判断是否通过并展示遮罩
    const Mask = (item: levelListType, v: number) => {
        // if (item.is_light === '1') {
        return (
            <div>
                <img src={item.cover_img} />
                <div className={styles.title}>{`关卡${v + 1}:${item.name}`}</div>
                <div className={styles.describe}>{item.description}</div>
                <div className={renderData[value] && renderData[value] && item.is_player === '1' ? styles.pass : styles.lock} />
            </div>
        )
        // } else {
        //     return <div className={styles.mask}>{`关卡${v + 1}:${item.name}`}</div>
        // }
    }
    //判断展示的按钮
    const showButton = () => {
        // if (value === i) {
        return (
            <div
                className={
                    styles.button
                    // renderData[value] && renderData[value].is_light === '1'
                    //     ? styles.button
                    //     : styles.un_pass
                }
                onClick={() => startTask(renderData[value], value)}
            >
                <span>
                    {/* {renderData[value] && renderData[value] && renderData[value].is_light === '1'
                        ? '开始任务'
                        : '等待解锁'} */}
                    进入关卡
                </span>
            </div>
        )
        // } else {
        //     return null
        // }
    }
    //轮播图主体
    const verticalItems = renderData.map((item: levelListType, index: number) => (
        <Swiper.Item key={index}>
            <div className={value === index ? styles.checked_content : styles.content}>{Mask(item, index)}</div>
        </Swiper.Item>
    ))

    useEffect(() => {
        if (swiperRef.current) {
            swiperRef.current.swipeTo(value)
        }
    }, [value])

    return (
        <div className={styles.page}>
            <Swiper
                ref={swiperRef}
                onIndexChange={v => {
                    // setValue(v)
                    getSwiperValue(v)
                }}
                indicator={() => null}
                slideSize={70}
                trackOffset={5}
                stuckAtBoundary={false}
            >
                {verticalItems}
            </Swiper>
            {/* {isSubmitTraining === false &&
                (isAllPlay() && !isSubmitTraining ? (
                    <div className={styles.button} onClick={onSubmit}>
                        <span>提交实训</span>
                    </div>
                ) : (
                ))} */}
            {showButton()}
        </div>
    )
})
